from django.shortcuts import render
from timeseries.arima import Arima
from BigDataWeb.view import get_algorithm
from BigDataWeb.view import put_algorithm
from BigDataWeb.view import read_data_source


def arima(request):
    context = {}
    algorithm = Arima()
    algorithm.user_id = request.session["login_name"]
    put_algorithm(algorithm)
    context["algorithm"] = algorithm
    return render(request, "timeseries/1.html", context)


def select_data_source(request):
    context = {}
    algorithm = get_algorithm(request)
    read_data_source(request, algorithm)
    context["algorithm"] = algorithm
    return render(request, "timeseries/2.html", context)


def understand_data_set(request):
    context = {}
    algorithm = get_algorithm(request)
    algorithm.setTimeAndValueFieldName(request.POST.get("time_field_name"), request.POST.get("value_field_name"))
    algorithm.checkAdfAndWn()
    context["algorithm"] = algorithm
    return render(request, "timeseries/3.html", context)


def configure_parameters(request):
    context = {}
    algorithm = get_algorithm(request)
    algorithm.diff_degrees = int(request.POST.get("diff_degrees"))
    algorithm.forcast_period_cnt = int(request.POST.get("forcast_period_cnt"))
    if algorithm.algorithm_name == "ARIMA模型":
        if request.POST.get("p"):
            algorithm.p = int(request.POST.get("p"))
        if request.POST.get("q"):
            algorithm.q = int(request.POST.get("q"))
    algorithm.implent()
    algorithm.saveToExcle()
    algorithm.generateNotebookFile()
    # 整理预测值forcast_values
    forcast_values = []
    for i in range(0, algorithm.forcast_period_cnt):
        # 预测值,误差
        forcast_values.append([algorithm.forcast_reuslt[0][i], algorithm.forcast_reuslt[1][i]])
    context["forcast_values"] = forcast_values
    context["algorithm"] = algorithm
    return render(request, "timeseries/5.html", context)
